package com.aptech.action;

import com.aptech.business.CustomerBusiness;
import com.aptech.dto.Customer;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;   
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AddCustomerAction extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            String id = request.getParameter("id");
            String name = request.getParameter("name");
            String des = request.getParameter("des");

            if (id == null || id.trim().equals("")) {
                request.setAttribute("customer_err", "Customer ID can't be blank.");
                request.getRequestDispatcher("/customer/addCustomer.jsp").forward(request, response);
                return;
            }

            Customer cust = CustomerBusiness.getCustomerByName(id);
            if (cust == null) {
                cust = new Customer();
                cust.setCustId(id);
                cust.setCustName(name);
                cust.setDescription(des);
                CustomerBusiness.insertCustomer(cust);

                request.setAttribute("customer_msg", "You have added customer '" + id + "-" + name + "'");
                request.getRequestDispatcher("/getCustomerList").forward(request, response);
            } else {
                request.setAttribute("customer_err", "Customer with ID = '" + id +  "' already existed");
                request.getRequestDispatcher("/customer/addCustomer.jsp").forward(request, response);
            }

        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            Logger.getLogger(AddCustomerAction.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            ex.printStackTrace();
            Logger.getLogger(AddCustomerAction.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            ex.printStackTrace();
            Logger.getLogger(AddCustomerAction.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
            Logger.getLogger(AddCustomerAction.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
